<!-- word模板预览页 -->
<template>
  <div class="word-preview-box">
    <div class="content-box">
      <!-- 图片预览区域 -->
      <div class="left">
        <!-- 图片列表 -->
        <div class="img-list-box">
          <c-scrollbar trigger="hover" style="height: 600px">
            <div
                v-for="(item, index) in wordInfo.previewUrl"
                :key="index"
                :class="['img-item-box', { active: currentIndex === index }]"
                @click="selectPreUrl(item, index)"
            >
              <el-image style="width: 150px; height: 200px" :src="item" fit/>
            </div>
          </c-scrollbar>
        </div>
        <!-- 图片大图展示 -->
        <div class="img-big-preview">
          <div class="big-img-box">
            <el-image style="width: 400px; height: 550px" :src="bigPreviewUrl" fit/>
          </div>
        </div>
      </div>
      <!-- 模板信息介绍页 -->
      <div class="right">
        <!-- 操作区 -->
        <div class="top">
          <h1>{{ wordInfo.name }}</h1>
          <div class="download-btn">
            <div class="button" @click="download(wordInfo.payIntegral)">
              <div v-if="!isPay" class="how-much"
              >{{ wordInfo.payIntegral }}<img width="20" src="@/assets/images/jianB.png" alt="积分"
              /></div>
              <span>立即下载</span>
            </div>
          </div>
          <div class="views-downs-box">
            <div class="icon-box">
              <svg-icon icon-name="icon-xiazailiang" color="#a3abb1" size="22px"></svg-icon>
              <span class="number downloads">{{ wordInfo.downloadCount }}</span>
            </div>
            <div class="icon-box">
              <svg-icon icon-name="icon-liulanliang1" color="#a3abb1" size="22px"></svg-icon>
              <span class="number">{{ wordInfo.views }}</span>
            </div>
            <div class="icon-box">
              <svg-icon icon-name="icon-pinglun1" color="#a3abb1" size="22px"></svg-icon>
              <span class="number">{{ wordInfo.commentCount }}</span>
            </div>
          </div>
        </div>
        <!-- 详细信息展示区 -->
        <div class="info-box">
          <h1>简历信息</h1>
          <div class="profile-box">
            <span class="label">简介</span>
            <p>{{ wordInfo.profile }}</p>
          </div>
          <div class="profile-box">
            <span class="label">分类</span>
            <p v-for="(item, index) in wordInfo.categoryList" :key="index" class="category">{{ item }}</p>
          </div>
          <div class="profile-box">
            <span class="label">标签</span>
            <p v-for="(item, index) in wordInfo.tagList" :key="index" class="category">{{ item }}</p>
          </div>
          <div class="profile-box">
            <span class="label">页数</span>
            <p>{{ wordInfo.pages }} 页</p>
          </div>
        </div>
      </div>
    </div>
    <div class="bottom-box">
      <!-- 轮播图 -->
      <word-carousel
          v-if="wordInfo.previewUrl"
          :preview-url-list="wordInfo.previewUrl"
      ></word-carousel>
    </div>

    <!-- 评论组件 -->
    <comment-com width="1200px"
                 :biz-id="id"
                 biz-type="5"
    >
    </comment-com>

    <!-- 获取积分弹窗 -->
    <get-integral-dialog
        :dialog-get-integral-visible="dialogGetIntegralVisible"
        @cancle="cancleDialog"
    ></get-integral-dialog>
    <!--下载进度条-->
    <el-dialog v-model="fullscreenLoading" title="正在下载文件，请稍候..." :close-on-click-modal="false"
               :close-on-press-escape="false" :show-close="false" width="20%">
      <div style="text-align: center;">
        <el-progress type="circle" :percentage="percentage"></el-progress>
      </div>
    </el-dialog>
    <!-- 回到顶部 -->
    <el-backtop :right="50" :bottom="80"/>
  </div>
</template>
<script lang="ts" setup>
import LoginDialog from '@/components/LoginDialog/LoginDialog';
import WordCarousel from './components/WordCarousel.vue';
import {
  getWordCategoryListAsync,
  getWordTemplateInfoAsync,
  wordDownloadUrl
} from '@/http/api/wordTemplate';
import {downloadFileUtil} from '@/utils/common';
import {payIntegralLogAsync} from '@/http/api/integral';
import appStore from '@/store';
import {useUserIsPayGoods} from '@/hooks/useUsrIsPayGoods';
// 获取word模板id
const route = useRoute();
const {id} = route.query;
const currentIndex = ref<number>(-1); // 选中哪一张预览图

// 查询模板详细信息
const wordInfo = ref<any>([]);

const getWordTemplateInfo = async () => {
  const data = await getWordTemplateInfoAsync(id);
  if (data.code === 200) {
    wordInfo.value = data.data;
    wordInfo.value.previewUrl = wordInfo.value.previewUrls;
    bigPreviewUrl.value = wordInfo.value.coverUrl;
    currentIndex.value = 0;
  } else {
    ElMessage.error(data.msg);
  }
};
getWordTemplateInfo();

// 图片预览大图
const bigPreviewUrl = ref<string>('');
// 点击预览图
const selectPreUrl = (item: any, index: number) => {
  bigPreviewUrl.value = item;
  currentIndex.value = index;
};

// 查询用户是否消费过该资源
const isPay = ref<any>(false);
onMounted(async () => {
  isPay.value = await useUserIsPayGoods("5", id);
});

// 点击立即下载
const download = async (payIntegral: number) => {
  let token = localStorage.getItem('token');
  if (!token) {
    LoginDialog(true);
    LoginDialog(true, '', async () => {
      isPay.value = await useUserIsPayGoods("5", id);
    });
  } else {
    // 判断用户是否支付过
    if (isPay.value) {
      await downloadTemplate();
    } else {
      // 判断当前用户积分是否充足
      const userIntegralTotal = appStore.useUserInfoStore.userIntegralInfo.integralTotal;
      if (userIntegralTotal < payIntegral) {
        ElMessage.warning('您的积分数量不足！');
        openGetDialog();
        return;
      } else {
        ElMessageBox.confirm(`确定消费${payIntegral}积分下载模板？只需一次支付，即可多次下载！`, '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
            .then(async () => {
              // 消费金币
              let params = {
                integralType: '4',
                bizType: '5',// 下载简历模板
                bizId: id // 模板id
              };
              const payData = await payIntegralLogAsync(params);
              if (payData.code === 200) {
                await downloadTemplate();
              } else {
                ElMessage.error('积分扣除错误！');
              }
            })
            .catch(() => {
            });
      }
    }
  }
};

// 打开获取积分弹窗
const dialogGetIntegralVisible = ref<boolean>(false);
const openGetDialog = () => {
  dialogGetIntegralVisible.value = true;
};

// 关闭弹窗
const cancleDialog = () => {
  dialogGetIntegralVisible.value = false;
};
const fullscreenLoading = ref(false)
const percentage = ref(0)
let timer: any = null;
// 下载文件
const downloadTemplate = async () => {
  const data = await wordDownloadUrl(id);
  fullscreenLoading.value = true
  timer = setInterval(() => {
    percentage.value += 5;
    if (percentage.value > 95) {
      percentage.value = 99;
      clearInterval(timer);
    }
  }, 500);
  // if (data.code === 200) {
  //   ElMessage.success('下载成功');
  //   // let url = data.data;
  //   // downloadFileUtil(url);
  //   isPay.value = await useUserIsPayGoods("5", id); // 更新用户是否支付过的状态
  // } else {
  //   ElMessage.error(data.msg);
  // }
  if (data.code) {
    fullscreenLoading.value = false
    ElMessage.error('网络过慢，请求超时，请重新尝试导出');
    return;
  } else {
    percentage.value = 100;
    fullscreenLoading.value = false
    isPay.value = await useUserIsPayGoods("5", id); // 更新用户是否支付过的状态
    const blob = new Blob([data]);
    const downloadElement = document.createElement('a');
    const href = window.URL.createObjectURL(blob); //创建下载的链接
    downloadElement.href = href;
    downloadElement.download = `${wordInfo.value.fileName}`; //下载后的文件名，根据需求定义
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  }
  percentage.value = 0;
  clearInterval(timer);
};
</script>
<style lang="scss" scoped>
.word-preview-box {
  width: 100%;
  font-family: '微软雅黑';

  .content-box {
    margin: 0 auto;
    min-height: 500px;
    padding: 20px 0;
    width: 1200px;
    display: flex;

    .left {
      display: flex;
      justify-content: space-between;

      .img-list-box {
        width: 160px;
        max-height: 600px;
        display: flex;
        flex-direction: column;
        justify-content: flex-start;

        .img-item-box {
          height: 202px;
          width: 152px;
          margin-bottom: 10px;
          cursor: pointer;
          transition: all 0.3s;
          border: 1px solid transparent;
          border-radius: 5px;
          overflow: hidden;

          &:hover {
            border: 1px solid #5b3562;
          }
        }

        .active {
          border: 1px solid #5b3562;
        }
      }

      .img-big-preview {
        margin-left: 30px;

        .big-img-box {
          background: #e7e7e7;
          padding: 24px 21px;
          border-radius: 3px;
        }
      }
    }

    .right {
      flex: 1;
      margin-left: 30px;
      display: flex;
      flex-direction: column;

      .top {
        height: 220px;
        width: 100%;
        background-color: #fff;
        margin-bottom: 20px;
        padding: 20px 30px 0 20px;
        display: flex;
        flex-direction: column;

        h1 {
          font-size: 22px;
          margin-bottom: 30px;
          text-align: justify;
          line-height: 1.5;
        }

        .download-btn {
          .button {
            width: 50%;
            height: 38px;
            margin-right: 20px;
            line-height: 38px;
            text-align: center;
            letter-spacing: 2px;
            color: #fff;
            font-size: 14px;
            background-image: -webkit-linear-gradient(to right, #2ddd9d, #1cc7cf);
            background-image: -moz-linear-gradient(to right, #2ddd9d, #1cc7cf);
            background-image: -ms-linear-gradient(to right, #2ddd9d, #1cc7cf);
            background-image: linear-gradient(to right, #2ddd9d, #1cc7cf);
            -webkit-border-radius: 50px;
            -moz-border-radius: 50px;
            border-radius: 50px;
            background-color: #2ddd9d;
            -webkit-transition: all 0.3s;
            -moz-transition: all 0.3s;
            -ms-transition: all 0.3s;
            -o-transition: all 0.3s;
            transition: all 0.3s;
            cursor: pointer;
            user-select: none;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover {
              opacity: 0.8;
            }

            .how-much {
              display: flex;
              align-items: center;
              margin-right: 5px;

              img {
                margin: 0 5px;
              }
            }
          }
        }

        .views-downs-box {
          margin-top: 50px;
          border-top: 1px solid #eee;
          flex: 1;
          color: #b2bcc3;
          display: flex;
          align-items: center;

          .icon-box {
            margin-right: 30px;
            display: flex;
            align-items: center;

            .number {
              padding-top: 1px;
              font-size: 18px;
              margin-left: 10px;
            }

            .downloads {
              margin-left: 6px;
              font-size: 18px;
            }
          }
        }
      }

      .info-box {
        width: 100%;
        background-color: #fff;
        padding: 20px 30px 20px 20px;
        display: flex;
        flex-direction: column;

        h1 {
          font-size: 16px;
          color: #515151;
          padding-bottom: 22px;
          border-bottom: 1px solid #ebebeb;
        }

        .profile-box {
          display: flex;
          margin: 10px 0;

          span {
            font-size: 14px;
            color: #555;
            margin-right: 15px;
          }

          p {
            font-size: 14px;
            color: #999999;
            padding: 0 15px;
          }

          .category {
            border-right: 1px solid #eee;
          }
        }
      }
    }
  }

  .bottom-box {
    margin: 30px auto;
    min-height: 500px;
    padding: 20px 0;
    width: 1200px;
    display: flex;
    background-color: #fff;
    display: flex;
  }
}
</style>
